<script type="text/javascript">
    //创建地图
    var timeVal,pointSimplifierIns,geolocation,bounds,code,sign,level,center,init = 0,cycle = 15000;
    var map = new AMap.Map('contain',{
        zooms:[10,18]
    });
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: false,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy:false,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            // noIpLocate:3
        });
        map.addControl(geolocation);
        tip('定位中……');
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });

    //解析定位结果
    function onComplete(data) {
        geolocation.getCityInfo(function (status,result) {
            var code_tmp = new Array();
            if(status==='complete'){
                code_tmp.key = 'city';
                code_tmp.value = result.adcode;
            }else{
                code_tmp.key = 'ad';
                code_tmp.value = data.addressComponent.adcode;
            }
            code = JSON.stringify(code_tmp);
            bound();
            initMarker('init');
        });
    }

    //解析定位错误信息
    function onError(data) {
        bound();
        initMarker('init');
    }

    map.on('movestart',function () {
        if(init>0 && sign != 'plate'){
            $('#loadingTip').remove();
            pointSimplifierIns.setData(null);
            clearInterval(timeVal);
        }
    });

    map.on('moveend',function (){
        if(sign != 'plate'){
            bound();
        }
        if(init>0 && sign != 'plate'){
            tip('加载数据，请稍候...');
            combine(sign);
        }
        init++;
    });

    //获取视图中的对角点
    function bound() {
        var bound = map.getBounds();
        var northeast = new Array();
        var southwest = new Array();
        var temp = new Array();
        northeast[0] = bound.northeast.lng;
        northeast[1] = bound.northeast.lat;
        southwest[0] = bound.southwest.lng;
        southwest[1] = bound.southwest.lat;
        temp[0] = northeast;
        temp[1] = southwest;
        bounds = JSON.stringify(temp);
        level = map.getZoom();
        center = map.getCenter();
    }

    //加载海量点插件
    function initMarker(type) {
        AMapUI.load(['ui/misc/PointSimplifier', 'lib/$'], function(PointSimplifier, $) {
            if (!PointSimplifier.supportCanvas) {
                alert('当前环境不支持 Canvas！');
                return;
            }
            tip('加载数据，请稍候...');
            //启动页面
            initPage(PointSimplifier,type);
        });
    }

    function tip(mes) {
        $("#loadingTip").remove();
        $('<div id="loadingTip">'+mes+'</div>').appendTo(document.body);
    }

    function initPage(PointSimplifier,type) {
        var groupStyleMap;
        //创建组件实例
        pointSimplifierIns = new PointSimplifier({
            zIndex: 300,
            map: map,
            autoSetFitView: false,
            getPosition: function(item) {
                if (!item) {
                    return null;
                }
                return item['location']['coordinates'];
            },
            getHoverTitle: function(dataItem, idx) {
                return dataItem['location']['coordinates'].join(',');
            },
            //使用GroupStyleRender
            renderConstructor: PointSimplifier.Render.Canvas.GroupStyleRender,
            renderOptions: {
                //点的样式
                pointStyle: {
                    //宽度
                    width: 0,
                    //高度
                    height: 0,
                    fillStyle: null,//'#A2D0FA',
                    strokeStyle: null
                },
                pointHoverStyle:{
                    content:'none'
                },
                getGroupId: function(item, idx) {
                    var id;
                    switch (item.authType) {
                        case 1:
                        case 2:
                            switch (item.driverStatus){
                                case 1:
                                    id = 2;
                                    break;
                                case 2:
                                case 3:
                                case 4:
                                    id = 1;
                                    break;
                                default:
                                    id = 0;
                                    break;
                            }
                            break;
                        default:
                            switch (item.driverStatus){
                                case 2:
                                    id = 2;
                                    break;
                                case 1:
                                case 3:
                                    id = 1;
                                    break;
                                default:
                                    id = 0;
                                    break;
                            }
                            break;
                    }
                    return id;
                },
                groupStyleOptions: function(gid) {
                    return groupStyleMap[gid];
                }
            }
        });
        function onIconLoad() {
            pointSimplifierIns.renderLater();
        }
        function onIconError(e) {
            console.log(e);
        }
        groupStyleMap = {
            '0': {
                pointStyle: {
                    //绘制点占据的矩形区域---------离线
                    content: PointSimplifier.Render.Canvas.getImageContent(
                        '{$offline}', onIconLoad, onIconError),
                    //宽度
                    width: 44,
                    //高度
                    height: 14,
                    //定位点为中心
                    offset: ['-50%', '-50%'],
                    fillStyle: null,
                    strokeStyle: null
                }
            },
            '1': {
                pointStyle: {
                    //绘制点占据的矩形区域---------行程中
                    content: PointSimplifier.Render.Canvas.getImageContent(
                        '{$trip}', onIconLoad, onIconError),
                    //宽度
                    width: 44,
                    //高度
                    height: 14,
                    //定位点为中心
                    offset: ['-50%', '-50%'],
                    fillStyle: null,
                    strokeStyle: null
                }
            },
            '2': {
                pointStyle: {
                    //绘制点占据的矩形区域---------接单中
                    content: PointSimplifier.Render.Canvas.getImageContent(
                        '{$order}', onIconLoad, onIconError),
                    //宽度
                    width: 44,
                    //高度
                    height: 14,
                    //定位点为中心
                    offset: ['-50%', '-50%'],
                    fillStyle: null,
                    strokeStyle: null
                }
            },
        };
        combine(type);
        pointSimplifierIns.on('pointClick', function(e, record) {
            var data = record.data;
            if((data.authType==3&&(data.driverStatus==1||data.driverStatus==3))||
                ((data.authType==1||data.authType==2)&&(data.driverStatus==2||data.driverStatus==3||data.driverStatus==4))){
                //实例化信息窗体
                $.post('{$url_order}',{driver_id:data.driverId,auth_type:data.authType},function (res) {
                    if(res['status']){
                        var infoWindow = new AMap.InfoWindow({
                            isCustom: true,  //使用自定义窗体
                            content: res['html'],
                            offset: new AMap.Pixel(170, 170),
                            closeWhenClickMap:true
                        });
                        infoWindow.open(map,new AMap.LngLat(data['location']['coordinate'][0],data['location']['coordinate'][1]));
                    }else{
                        layer.alert(res['msg'],{icon:2})
                    }
                });
            }else{
                window.open('{$url}'+'?driver_id='+data.driverId+'&auth_type='+data.authType,'_blank');
            }
        });
    }

    function combine(type) {

        page(type);
        timeVal = setInterval(page,cycle,type);
    }
    //获取范围内的车辆数---分页获取
    function page(type) {
        $.ajax({
            type: 'post',
            async: false,
            url: '{$url_page}',
            data: {
                bounds: bounds,
                type: type
            },
            success: function (res) {
                var page = res['page'], temp,sta_={},points=[],flag =true;
                for (var p = 1; p <= page; p++) {
                    temp = createPoints(type, p);
                    if(temp['status']!=1){
                        tip(temp['msg']);
                        flag = false;
                        break;
                    }
                    points =  points.concat(temp['data']);
                    if(p==1){
                        sta_ = temp['sta'];
                    }
                }
                if(flag){
                    pointSimplifierIns.setData(points);
                    if(type == 'plate'){
                        console.log(points);
                        $('#statistic').hide();
                        map.setCenter(points[0]['location']['coordinates']);
                    }
                    else{
                        setSta(sta_);
                        $('#statistic').show();
                    }
                    $('#loadingTip').remove();
                }
            }
        });
    }
    //设置数据源，data需要是一个数组
    var createPoints = function (type,page,flag) {
        var data = [];
        data['status'] = 0;
        data['msg'] = "暂无数据";
        $.ajax({
            type:'post',
            url:'{$url_all}',
            async: false,
            data:{
                type : type,
                bounds : bounds,
                inner : inner,
                inter : inter,
                page: page
            },
            beforeSend:function () {
                if(flag){
                    return false;
                }
            },
            success:function(csv) {
                data =  csv;
            }
        });
        return data;
    };

    //设置统计信息
    function setSta(data) {
        $('#total').html(data['total']);
        $('#taking').html(data['taking']);
        $('#trip').html(data['trip']);
        $('#offline').html(data['offline']);
    }
</script>